package com.mbl.base.core.common.constant;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mbl.base.modular.config.entity.Dict;
import com.mbl.base.modular.config.mapper.DictMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@DependsOn("springContextHolder")
public class MblConstantFactory {
    private DictMapper dictMapper = SpringContextHolder.getBean(DictMapper.class);
    public static MblConstantFactory me() {
        return SpringContextHolder.getBean("mblConstantFactory");
    }

    /**
     * 根据字典code获取字典子列表 pid 代表顶级字典列表
     * @param code
     * @return
     */
    public List<Dict> getDictListByCode(String code){
        if(StringUtils.isBlank(code)){
            return null;
        }
        Long pid = 0l;
        if(!code.toLowerCase().equals("pid")){ // 如果code 不是pid 则进行字典子列表查询
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("code", code);
            final Dict dict = dictMapper.selectOne(queryWrapper);
            pid = dict.getId();
        }
        QueryWrapper<Dict> wrapper = new QueryWrapper();
        wrapper.eq("dict_pid", pid);
        final List<Dict> list = dictMapper.selectList(wrapper);
        return list;
    }

    /**
     * 根据字典code获取字典值
     * @param code
     */
    public String getDictValByCode(String code) {
        QueryWrapper<Dict> wrapper = new QueryWrapper();
        wrapper.eq("code", code);
        final Dict dict = dictMapper.selectOne(wrapper);
        if(dict == null){
            return null;
        }
        return dict.getVal();
    }
}
